package com.example.androidhomework;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author coderxshuai
 * @date 2021/4/1
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {
    /**
     * 上一首按钮
     */
    Button btnPre;
    /**
     * 暂停/停止按钮
     */
    Button btnPausePlay;
    /**
     * 下一首按钮
     */
    Button btnNext;
    /**
     * 进度条
     */
    SeekBar seekBar;
    /**
     * 歌曲列表控件
     */
    ListView listView;
    /**
     * 歌曲列表
     */
    List<String> songList = new ArrayList<>();
    /**
     * 音乐播放器
     */
    MediaPlayer mediaPlayer;
    /**
     * 当前播放歌曲下标
     */
    int currentSong = -1;
    /**
     * 当前音乐总时长
     */
    int duration = 0;
    ProgressTask task;
    /**
     * 默认音乐存放路径
     */
    public final String MUSIC_PATH = "/storage/emulated/0/Music/";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnPre = findViewById(R.id.btn_pre);
        btnPausePlay = findViewById(R.id.btn_pause_play);
        btnNext = findViewById(R.id.btn_next);
        seekBar = findViewById(R.id.seek_bar);
        listView = findViewById(R.id.list_view);
        mediaPlayer = new MediaPlayer();
        //检查权限
        checkNeedPermissions();
        //初始化音乐列表
        initSong();
        //ListView的适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this, android.R.layout.simple_list_item_1, songList.toArray(new String[songList.size()]));
        listView.setAdapter(adapter);
        //ListView的点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //点击播放
                playSong(i);
            }
        });
        //为下列按钮注册单击事件
        btnNext.setOnClickListener(this);
        btnPausePlay.setOnClickListener(this);
        btnPre.setOnClickListener(this);
        //进度条的进度条位置发生变化的监听事件
        seekBar.setOnSeekBarChangeListener(this);
        //当前歌曲完成的监听事件
        mediaPlayer.setOnCompletionListener(this);
    }

    /**
     * @param view 点击的控件
     */
    @Override
    public void onClick(View view) {
        //根据控件ID确定点击的事件
        switch (view.getId()) {
            case R.id.btn_pre:
                playSong((currentSong - 1 + songList.size()) % songList.size());
                break;
            case R.id.btn_pause_play:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                } else {
                    if (currentSong == -1) {
                        playSong(0);
                    } else {
                        mediaPlayer.start();
                    }
                }
                break;
            case R.id.btn_next:
                playSong((currentSong + 1 + songList.size()) % songList.size());
                break;
            default:
                break;
        }
    }

    /**
     * 获取所有歌曲
     */
    public void initSong() {
        File filePath = new File(MUSIC_PATH);
        File[] files = filePath.listFiles();
        for (File f : files) {
            songList.add(f.getName());
        }
    }

    /**
     * 检查权限
     */
    private void checkNeedPermissions() {
        //6.0以上需要动态申请权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
        }
    }

    /**
     * 播放歌曲
     *
     * @param i 需要播放歌曲的下标
     */
    private void playSong(int i) {
        //先停止当前歌曲播放
        mediaPlayer.stop();
        mediaPlayer.reset();
        try {
            //设定需要播放的歌曲
            mediaPlayer.setDataSource("/storage/emulated/0/Music/" + songList.get(i));
            mediaPlayer.prepare();
            mediaPlayer.start();
            //通过AsyncTask对进度条进行更新
            task = new ProgressTask();
            task.execute();
            //获取当前歌曲的总时长
            duration = mediaPlayer.getDuration();
            //设置进度条的最大值
            seekBar.setMax(duration);
            //更新当前播放歌曲的下标
            currentSong = i;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放
        mediaPlayer.release();
        if (task != null) {
            task.cancel(true);
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        //下一首播放
        playSong((currentSong + 1 + songList.size()) % songList.size());
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //重新定位
        mediaPlayer.seekTo(seekBar.getProgress());
    }

    class ProgressTask extends AsyncTask<Void, Integer, Boolean> {
        @Override
        protected Boolean doInBackground(Void... voids) {
            do {
                //获取当前播放位置
                int position = mediaPlayer.getCurrentPosition();
                //更新进度条
                publishProgress(position);
            } while (mediaPlayer.isPlaying());
            return true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            //设置进度条位置
            seekBar.setProgress(values[0]);
        }
    }
}

